package dk.eclipse.android.badassapp.helper;

import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.telephony.SmsManager;
import android.widget.ProgressBar;
import android.widget.Toast;

/**
 * This helper class handles operations for sending SMS's and receiving delivery
 * reports.
 * 
 * @author Ronni Kahalani
 * 
 */
public class SMSHelper {

	private static final String INTENT_ACTION_SMS_SENT = "SMS_SENT";
	private static final String INTENT_ACTION_SMS_DELIVERED = "SMS_DELIVERED";

	private static final String MSG_SMS_SENDING = "Sending SMS to: %s";

	private static int nextNotificationId = 0;


	/**
	 * Sends an SMS to a phone number.
	 * 
	 * @param context
	 * @param phoneNumber
	 * @param message
	 * @param deliveryReport
	 * @param progressBar
	 */
	public static void sendSMS(final Context context, final String phoneNumber,
			final String message, final boolean deliveryReport,
			final ProgressBar progressBar, int smsSentIconResourceId, int smsDeliveredIconResourceId) {

		PendingIntent sentPI = PendingIntent.getBroadcast(context, 0,
				new Intent(INTENT_ACTION_SMS_SENT), 0);
		PendingIntent deliveredPI = null;

		// ---when the SMS has been sent---
		int notificationId = nextNotificationId++;
		
		// Set up the SMS sent broadcast receiver.
		SMSSentBroadcastReciever smsSentBroadcastReciever = new SMSSentBroadcastReciever(notificationId, smsSentIconResourceId,  phoneNumber, message, progressBar);
		context.registerReceiver(smsSentBroadcastReciever, new IntentFilter(INTENT_ACTION_SMS_SENT));

		// Does the user want a delivery report.
		if (deliveryReport) {

			deliveredPI = PendingIntent.getBroadcast(context, 0, new Intent(
					INTENT_ACTION_SMS_DELIVERED), 0);

			// Set up the SMS delivered broadcast receiver.
			SMSDeliveredBroadcastReciever smsDeliveredBroadcastReciever = new SMSDeliveredBroadcastReciever(notificationId, smsDeliveredIconResourceId,  phoneNumber, message, progressBar);
			context.registerReceiver( smsDeliveredBroadcastReciever, new IntentFilter(INTENT_ACTION_SMS_DELIVERED));

		}

		// Switch on the progress indicator.
		if(progressBar != null) {
			progressBar.setVisibility(ProgressBar.VISIBLE);
		}

		// Tell the user that the SMS is being sent.
		NotificationHelper.sendToast(context, String.format(
				MSG_SMS_SENDING, new Object[] { phoneNumber}),
				Toast.LENGTH_SHORT);

		// Get the SMS manager and send the SMS.
		SmsManager sms = SmsManager.getDefault();
		sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);

	}
	
	

}

